package com.dongdongqiang.daogenerator.sqlbuilder.mysql;

import com.dongdongqiang.daogenerator.pojo.TableColumn;
import com.dongdongqiang.daogenerator.pojo.TableMeta;
import com.dongdongqiang.daogenerator.sqlbuilder.UpdateSQLBuilder;

import java.util.List;

/**
 * Created by ZZB on 2017/10/19.
 */
public class MysqlUpdateSQLBuilder implements UpdateSQLBuilder {
    private final static String UPDATE_SQL = "update {tableName} set {columns} where {pk} = ?;";
    private final static String UPDATE_FIELD_SQL = "update {tableName} set {column} = ? where {pk} = ?;";
    private final static String UPDATE_LIST_FIELD_SQL = "update {tableName} set {column} = ? where {pk} in ({pks});";

    public String buildUpdateSQL(TableMeta tableMeta) {
        String tableName = tableMeta.getTableName();
        List<TableColumn> tableColumns = tableMeta.getTableColumns();
        if (tableColumns.size() == 0) return "";
        String columns = tableColumns.stream().filter(tableColumn -> !tableColumn.getColumnName().equals(tableMeta.getPrimaryKeyColumn().getColumnName()))
                .map(tableColumn -> "`"+tableColumn.getColumnName() + "` = ?").reduce((s, s2) -> s + "," + s2).get();
        return UPDATE_SQL.replace("{tableName}",tableName).replace("{columns}",columns)
                .replace("{pk}","`"+tableMeta.getPrimaryKeyColumn().getColumnName()+"`");
    }

    public String buildUpdateFieldSQL(TableMeta tableMeta,String column , Object value , Object pk){
        return UPDATE_FIELD_SQL
                .replace("{tableName}", tableMeta.getTableName())
                .replace("{column}", "`" + column + "`")
                .replace("{pk}", "`" + tableMeta.getPrimaryKeyColumn().getColumnName() + "`");
    }

    @Override
    public String buildUpdateListFieldSQL(TableMeta tableMeta, String column, Object value, List<?> pks) {
        return UPDATE_LIST_FIELD_SQL
                .replace("{tableName}", tableMeta.getTableName())
                .replace("{column}", "`" + column + "`")
                .replace("{pk}", "`" + tableMeta.getPrimaryKeyColumn().getColumnName() + "`")
                .replace("{pks}",pks.stream().map(o -> "?").reduce((s, s2) -> s + "," + s2 ).get());
    }
}
